<template>
  <div class="user-address-management">
    <!-- 页面标题 -->
    <lay-card>
      <template #header>
        <div class="page-header">
          <h2>用户地址管理</h2>
          <p>管理所有用户的收货地址信息</p>
        </div>
      </template>
    </lay-card>

    <!-- 搜索区域 -->
    <lay-card style="margin-top: 16px;">
      <lay-form :model="searchForm" ref="searchFormRef">
        <lay-row :space="16">
          <lay-col :md="6">
            <lay-form-item label="用户ID" prop="userId">
              <lay-input v-model="searchForm.userId" placeholder="请输入用户ID" />
            </lay-form-item>
          </lay-col>
          <lay-col :md="6">
            <lay-form-item label="收货人" prop="receiverName">
              <lay-input v-model="searchForm.receiverName" placeholder="请输入收货人姓名" />
            </lay-form-item>
          </lay-col>
          <lay-col :md="6">
            <lay-form-item label="手机号" prop="receiverPhone">
              <lay-input v-model="searchForm.receiverPhone" placeholder="请输入手机号" />
            </lay-form-item>
          </lay-col>
          <lay-col :md="6">
            <lay-form-item label="省份" prop="province">
              <lay-input v-model="searchForm.province" placeholder="请输入省份" />
            </lay-form-item>
          </lay-col>
        </lay-row>
        <lay-row :space="16">
          <lay-col :md="6">
            <lay-form-item label="城市" prop="city">
              <lay-input v-model="searchForm.city" placeholder="请输入城市" />
            </lay-form-item>
          </lay-col>
          <lay-col :md="6">
            <lay-form-item label="是否默认" prop="isDefault">
              <lay-select v-model="searchForm.isDefault" placeholder="请选择">
                <lay-select-option value="">全部</lay-select-option>
                <lay-select-option value="1">是</lay-select-option>
                <lay-select-option value="0">否</lay-select-option>
              </lay-select>
            </lay-form-item>
          </lay-col>
          <lay-col :md="12">
            <lay-form-item>
              <lay-button type="primary" @click="handleSearch">
                <lay-icon type="layui-icon-search" />
                搜索
              </lay-button>
              <lay-button @click="handleReset" style="margin-left: 8px;">
                <lay-icon type="layui-icon-refresh" />
                重置
              </lay-button>
            </lay-form-item>
          </lay-col>
        </lay-row>
      </lay-form>
    </lay-card>

    <!-- 地址列表 -->
    <lay-card style="margin-top: 16px;">
      <template #header>
        <div style="display: flex; justify-content: space-between; align-items: center;">
          <span>地址列表</span>
          <div>
            <!-- 已注释，管理员不可新增地址 -->
            <!-- <lay-button type="primary" size="sm" @click="handleCreate">
              <lay-icon type="layui-icon-add-1" />
              新增地址
            </lay-button> -->
            <!-- 已注释，管理员不可批量删除地址 -->
            <!-- <lay-button 
              type="danger" 
              size="sm" 
              :disabled="selectedAddresses.length === 0"
              @click="handleBatchDelete"
              style="margin-left: 8px;"
            >
              <lay-icon type="layui-icon-delete" />
              批量删除
            </lay-button> -->
          </div>
        </div>
      </template>

      <lay-table 
        :columns="columns" 
        :data-source="addressList" 
        :loading="loading"
        :pagination="false"
        @row-selection-change="handleSelectionChange"
        row-key="id"
      >
        <template #toolbar>
          <lay-checkbox 
            :model-value="selectedAddresses.length === addressList.length && addressList.length > 0"
            :indeterminate="selectedAddresses.length > 0 && selectedAddresses.length < addressList.length"
            @change="handleSelectAll"
            value="selectAll"
          />
        </template>

        <template #isDefault="{ data }">
          <lay-tag :type="data.isDefault === 1 ? 'primary' : 'normal'">
            {{ data.isDefault === 1 ? '默认' : '普通' }}
          </lay-tag>
        </template>

        <template #fullAddress="{ data }">
          <span>{{ data.province }}{{ data.city }}{{ data.district }}{{ data.address }}</span>
        </template>

        <template #operator="{ data }">
          <lay-button size="xs" @click="handleView(data)">查看</lay-button>
          <!-- 已注释，管理员不可编辑地址 -->
          <!-- <lay-button size="xs" type="primary" @click="handleEdit(data)" style="margin-left: 4px;">编辑</lay-button> -->
          <!-- 已注释，管理员不可删除地址 -->
          <!-- <lay-button 
            size="xs" 
            type="danger" 
            @click="handleDelete(data)" 
            style="margin-left: 4px;"
          >
            删除
          </lay-button> -->
          <!-- 已注释，管理员不可设置默认地址 -->
          <!-- <lay-button 
            v-if="data.isDefault === 0"
            size="xs" 
            type="warm" 
            @click="handleSetDefault(data)" 
            style="margin-left: 4px;"
          >
            设为默认
          </lay-button> -->
        </template>
      </lay-table>
      
      <!-- 自定义分页组件 -->
      <Pagination
        :total="pagination.total"
        :page="pagination.current"
        :page-size="pagination.pageSize"
        :page-size-options="pagination.limits"
        @change="handlePaginationChange"
        @update:page="handlePageChange"
        @update:page-size="handlePageSizeChange"
      />
    </lay-card>

    <!-- 地址详情/编辑对话框 -->
    <AddressDialog
      v-model="addressDialogVisible"
      :mode="addressDialogMode"
      :address-data="currentAddress"
      @success="handleDialogSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { layer } from '@layui/layui-vue'
import { UserApi } from '../../api/module/user'
import type { UserAddress } from '../../types/user'
import AddressDialog from './components/AddressDialog.vue'
import Pagination from '@/components/Pagination.vue'

// 响应式数据
const loading = ref(false)
const addressList = ref<UserAddress[]>([])
const selectedAddresses = ref<UserAddress[]>([])
const addressDialogVisible = ref(false)
const addressDialogMode = ref<'view' | 'create' | 'edit'>('view')
const currentAddress = ref<UserAddress | null>(null)

// 搜索表单
const searchForm = reactive<{
  userId: string
  receiverName: string
  receiverPhone: string
  province: string
  city: string
  isDefault: string
}>({
  userId: '',
  receiverName: '',
  receiverPhone: '',
  province: '',
  city: '',
  isDefault: ''
})

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showPage: true,
  showCount: true,
  showSkip: true,
  showLimit: true,
  limits: [10, 20, 50, 100]
})

// 表格列配置
const columns = [
  {
    title: '选择',
    width: '60px',
    type: 'checkbox',
    fixed: 'left'
  },
  {
    title: 'ID',
    key: 'id',
    width: '80px'
  },
  {
    title: '用户ID',
    key: 'userId',
    width: '100px'
  },
  {
    title: '收货人',
    key: 'receiverName',
    width: '120px'
  },
  {
    title: '手机号',
    key: 'receiverPhone',
    width: '130px'
  },
  {
    title: '完整地址',
    key: 'fullAddress',
    customSlot: 'fullAddress',
    minWidth: '300px'
  },
  {
    title: '邮政编码',
    key: 'postalCode',
    width: '100px'
  },
  {
    title: '是否默认',
    key: 'isDefault',
    customSlot: 'isDefault',
    width: '100px'
  },
  {
    title: '创建时间',
    key: 'createdAt',
    width: '160px'
  },
  {
    title: '操作',
    key: 'operator',
    customSlot: 'operator',
    width: '200px',
    fixed: 'right'
  }
] as any[]

// 获取地址列表
const fetchAddressList = async () => {
  try {
    loading.value = true
    
    // 过滤掉空字符串参数
    const filteredSearchForm = Object.keys(searchForm).reduce((acc, key) => {
      const value = (searchForm as any)[key]
      if (value !== '' && value !== null && value !== undefined) {
        acc[key] = value
      }
      return acc
    }, {} as any)
    
    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      ...filteredSearchForm
    }
    
    const response = await UserApi.getAllAddresses(params)
    
    addressList.value = response.data.list
    pagination.total = response.data.total
  } catch (error) {
    layer.msg('获取地址列表失败', { icon: 2 })
    console.error('获取地址列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchAddressList()
}

// 重置
const handleReset = () => {
  Object.keys(searchForm).forEach((key) => {
    (searchForm as any)[key] = ''
  })
  pagination.current = 1
  fetchAddressList()
}

// 分页变化处理
const handlePaginationChange = (page: number, pageSize: number) => {
  pagination.current = page
  pagination.pageSize = pageSize
  fetchAddressList()
}

// 页码变化处理
const handlePageChange = (page: number) => {
  pagination.current = page
  fetchAddressList()
}

// 每页数量变化处理
const handlePageSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize
  pagination.current = 1 // 重置到第一页
  fetchAddressList()
}

// 选择变化
const handleSelectionChange = (selectedKeys: string[], selectedRows: UserAddress[]) => {
  selectedAddresses.value = selectedRows
}

// 全选
const handleSelectAll = (checked: boolean) => {
  if (checked) {
    selectedAddresses.value = [...addressList.value]
  } else {
    selectedAddresses.value = []
  }
}

// 新增地址 - 已注释，管理员不可新增地址
// const handleCreate = () => {
//   currentAddress.value = null
//   addressDialogMode.value = 'create'
//   addressDialogVisible.value = true
// }

// 查看地址
const handleView = (address: UserAddress) => {
  currentAddress.value = address
  addressDialogMode.value = 'view'
  addressDialogVisible.value = true
}

// 编辑地址 - 已注释，管理员不可编辑地址
// const handleEdit = (address: UserAddress) => {
//   currentAddress.value = address
//   addressDialogMode.value = 'edit'
//   addressDialogVisible.value = true
// }

// 删除地址 - 已注释，管理员不可删除地址
// const handleDelete = (address: UserAddress) => {
//   layer.confirm(`确定要删除收货人"${address.receiverName}"的地址吗？`, {
//     icon: 3,
//     title: '删除确认',
//     yes: async (index: number) => {
//       try {
//         await UserApi.deleteUserAddress(address.userId, address.id!)
//         layer.msg('删除成功', { icon: 1 })
//         layer.close(index) // 关闭确认弹框
//         fetchAddressList()
//       } catch (error) {
//         layer.msg('删除失败', { icon: 2 })
//         layer.close(index) // 即使失败也要关闭弹框
//         console.error('删除地址失败:', error)
//       }
//     }
//   })
// }

// 批量删除 - 已注释，管理员不可批量删除地址
// const handleBatchDelete = () => {
//   if (selectedAddresses.value.length === 0) {
//     layer.msg('请选择要删除的地址', { icon: 3 })
//     return
//   }

//   layer.confirm(`确定要删除选中的 ${selectedAddresses.value.length} 个地址吗？`, {
//     icon: 3,
//     title: '批量删除确认',
//     yes: async (index: number) => {
//       try {
//         const deletePromises = selectedAddresses.value.map(address => 
//           UserApi.deleteUserAddress(address.userId, address.id!)
//         )
//         await Promise.all(deletePromises)
//         layer.msg('批量删除成功', { icon: 1 })
//         layer.close(index) // 关闭确认弹框
//         selectedAddresses.value = []
//         fetchAddressList()
//       } catch (error) {
//         layer.msg('批量删除失败', { icon: 2 })
//         layer.close(index) // 即使失败也要关闭弹框
//         console.error('批量删除地址失败:', error)
//       }
//     }
//   })
// }

// 设为默认地址 - 已注释，管理员不可设置默认地址
// const handleSetDefault = (address: UserAddress) => {
//   layer.confirm(`确定要将此地址设为默认地址吗？`, {
//     icon: 3,
//     title: '设置确认',
//     yes: async (index: number) => {
//       try {
//         await UserApi.setDefaultAddress(address.userId, address.id!)
//         layer.msg('设置成功', { icon: 1 })
//         layer.close(index) // 关闭确认弹框
//         fetchAddressList()
//       } catch (error) {
//         layer.msg('设置失败', { icon: 2 })
//         layer.close(index) // 即使失败也要关闭弹框
//         console.error('设置默认地址失败:', error)
//       }
//     }
//   })
// }

// 对话框成功回调
const handleDialogSuccess = () => {
  fetchAddressList()
}

// 页面加载时获取数据
onMounted(() => {
  fetchAddressList()
})
</script>

<style scoped>
.user-address-management {
  padding: 16px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 20px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

/* 表格样式优化 */
.lay-table {
  border-radius: 8px;
  overflow: hidden;
}

/* 按钮组样式 */
.lay-button + .lay-button {
  margin-left: 8px;
}

/* 标签样式 */
.lay-tag {
  border-radius: 4px;
}

/* 搜索表单样式 */
.lay-form .lay-form-item {
  margin-bottom: 16px;
}

/* 卡片样式 */
.lay-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 响应式优化 */
@media (max-width: 768px) {
  .user-address-management {
    padding: 8px;
  }
  
  .lay-col {
    margin-bottom: 16px;
  }
}
</style>